package demo3;


import java.util.Arrays;
import java.util.Objects;

public class HashBuck2<K,V> {

    //创建链表节点
    static class Node<K,V>{
        private K key;//key值
        private V val;//val值
        private Node<K,V> next;//存放下一个节点的地址

        //初始化这个节点
        public Node(K key,V val){
            this.key = key;
            this.val = val;
        }
    }
    //每个数组下标都存放着一个链表
    public Node<K,V>[] array;
    private static final double DEFAULT_LOAD_FACTOR = 0.75;//负载因子
    public int usedSize;//有效个数
    public HashBuck2(){
        //初始化hash桶
        this.array = (Node<K, V>[]) new Node[7];//初始化10个结点
    }

    //实现两个方法 put方法--->resize()扩容  和  get 方法

    public void put(K key,V val){
        int hash = key.hashCode();
        int index = hash % array.length;
        //如果key相同就覆盖val
        Node<K,V> cur = array[index];
        while(cur!=null){
            if(cur.key.equals(key)){
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        //如果key值不相等,那么我们就进行头插到这个index位置上
        Node<K,V> node = new Node<K,V>(key,val);
        node.next = array[index];
        array[index] = node;
        this.usedSize++;
        //现在已经头插完毕
        //如果超过负载因子就要扩容-->resize
        if(CheckDefaultLoadFactor()>DEFAULT_LOAD_FACTOR){
            array = resize(index);
        }

    }

    /**
     * 这里要注意扩容后要重新哈希
     */
    private Node<K,V>[] resize(int index){
        //将原来的数组扩容为原来的两倍并且放到一个新的数组
        Node<K,V>[] tmp = (Node<K, V>[]) new Node[2*array.length];
        //遍历这个下标的每个节点,对于每一个节点进行重新哈希
        Node<K,V> cur = array[index];
        while(cur!=null){
            Node<K,V> curNext = cur.next;
            //对于每一个节点进行重新哈希
            int hash = cur.key.hashCode();
            int reIndex = hash % tmp.length;
            cur.next = tmp[reIndex];
            tmp[reIndex] = cur;
            cur = curNext;
        }
        return  tmp;
    }

    private double CheckDefaultLoadFactor(){
        return (double)this.usedSize/this.array.length;
    }

    public V get(int key){
        //获取key的value值
        //先要根据这个key找到存储位置,然后遍历这个链表寻找
        int index = key% array.length;
        Node cur = array[index];
        while(cur!=null){
            if(cur.key.equals(key)){
                return (V)cur.val;
            }
            cur = cur.next;
        }
        return null;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        HashBuck2<?, ?> hashBuck2 = (HashBuck2<?, ?>) o;
        return usedSize == hashBuck2.usedSize && Arrays.equals(array, hashBuck2.array);
    }

    @Override
    public int hashCode() {
        int result = Objects.hash(usedSize);
        result = 31 * result + Arrays.hashCode(array);
        return result;
    }
}